package com.simons.module.export;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Configuration;

import com.simons.common.utils.date.DateUtils;
import com.simons.common.utils.file.PathUtil;
import com.simons.common.utils.file.office.ExcelFactory;
import com.simons.module.export.enums.PlanType;

import lombok.extern.log4j.Log4j2;
@Configuration
@Log4j2
public abstract class AbstractExportService {
	
	//导出的地方
	protected String exportPlace;
	
	//导出的excel的表头
	protected String[] headers;
	
	//导出的数据对应表头的字段
	protected String[] fieldNames;
	
	//导出的sheet名
	protected String sheetName;
	
	//导出的文件名
	protected String exportFileNamePre;
	
	//导出类型
	protected PlanType exportType;
	
	public abstract File export(Map<String,Object> params)throws Exception;
	
	/**
	 * 导出操作
	 */
	protected <T> File export(List<T> list) throws Exception {
		String fileName = getFileName(exportFileNamePre);
		return this.export(list, fileName, sheetName, fieldNames, headers, null);
	}
	
	/**
	 * 有枚举类型的导出操作
	 */
	protected <T> File exportByEnum(List<T> list, Map<String, Map<String, String>> enumMap) throws Exception {
		String fileName = getFileName(exportFileNamePre);
		return this.export(list, fileName, sheetName, fieldNames, headers, enumMap);
	}
	
	/**
	 * 导出操作
	 */
	private <T> File export(List<T> list, String fileName, String sheetName, String[] fieldNames, String[] headers, Map<String, Map<String, String>> enumMap) throws Exception {
		String fileExportName = exportPlace + PathUtil.FILE_SEPARATOR + exportType + PathUtil.FILE_SEPARATOR + fileName;

		log.info("文件的路径及名字为：" + fileExportName);

		File file = new File(fileExportName);

		if (!file.exists()) {
			// 先得到文件的上级目录，并创建上级目录，在创建文件
			file.getParentFile().mkdirs();
			// 创建文件
			file.createNewFile();
		}

		OutputStream out = null;
		
		try{
			out = new FileOutputStream(file);
			if(enumMap != null) {
				ExcelFactory.writeExcel2007(enumMap, fileName, out, sheetName, fieldNames, headers, list);
			} else {
				ExcelFactory.writeExcel2007(fileName, out, sheetName, fieldNames, headers, list);
			}
			out.flush();
		}finally{
			IOUtils.closeQuietly(out);
		}
		return file;
	}
	
	/**
	 * 获取文件前段名
	 */
	protected String getFileName(String fileNameHead){
		return fileNameHead+"_" + DateUtils.format(new Date(), "yyyy-MM-dd-HH_mm_ss") + ".xlsx";
	}
	

}
